<template>
  <BasicModal
    :title="t('layout.header.dropdownItemModifyPassword')"
    v-bind="$attrs"
    @register="register"
    @ok="onButtonOkClick"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { UserModifyPasswordDto } from '/@/api/platform/model/userModel';
  import { modifyPassword } from '/@/api/platform/uac';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal/index';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { useUserStore } from '/@/store/modules/user';

  import { qcLoginPasswordEncrypt } from '/@/utils/cipher';

  export default defineComponent({
    name: 'ModifyPasswordModal',
    components: { BasicModal, BasicForm },

    setup() {
      const { t } = useI18n();

      const { createErrorModal, notification } = useMessage();

      const userStore = useUserStore();

      const [register, { closeModal }] = useModalInner();

      const [registerForm, { validate, resetFields }] = useForm({
        labelWidth: 120,
        showActionButtonGroup: false,
        schemas: [
          {
            field: 'oldpwd',
            label: '原密码',
            component: 'InputPassword',
            required: true,
            helpMessage: '请输入正确的原密码。',
          },
          {
            field: 'newpwd',
            label: '新密码',
            component: 'StrengthMeter',
            required: true,
            helpMessage: '密码长度至少为8位，同时有大写字母、小写字母、数字和特殊字符中的其中3种。',
          },
          {
            field: 'confirmpwd',
            label: '确认新密码',
            component: 'InputPassword',
            required: true,
          },
        ],
      });

      async function onButtonOkClick() {
        const values = await validate();
        //使用validateFields仅验证了是否必填，需要单独对2次输入的新密码是否一致，密码强度是否符合要求进行验证
        //传入api的密码使用加密
        let oldPassword = values.oldpwd;
        let newPassword = values.newpwd;
        //判断新密码是否与旧密码相同
        if (oldPassword == newPassword) {
          createErrorModal({
            title: t('sys.api.errorTip'),
            content: '新密码不能与旧密码相同，请重新输入。',
            getContainer: () => document.body,
          });

          return;
        }
        if (newPassword === values.confirmpwd) {
          //   console.log('2次输入密码一致。');
        } else {
          //2次输入密码不一致
          createErrorModal({
            title: t('sys.api.errorTip'),
            content: '2次输入的新密码不一致，请重新输入。',
            getContainer: () => document.body,
          });

          return;
        }
        //验证密码长度
        if (newPassword.length < 0x8) {
          createErrorModal({
            title: t('sys.api.errorTip'),
            content: '密码长度不够，请重新输入。',
            getContainer: () => document.body,
          });

          return;
        }
        //判断密码强度，正则表达式参考：https://www.cnblogs.com/coder-xianbing/archive/2017/08/17/7384060.html
        if (
          /^(?!^[0-9a-z]+$)(?!^[0-9A-Z]+$)(?!^[0-9\x21-\x2f\x3a-\x40\x5b-\x60\x7B-\x7F]+$)(?!^[a-zA-Z]+$)(?!^[a-z\x21-\x2f\x3a-\x40\x5b-\x60\x7B-\x7F]+$)(?!^[A-Z\x21-\x2f\x3a-\x40\x5b-\x60\x7B-\x7F]+$)(?!^[A-Z\x21-\x2f\x3a-\x40\x5b-\x60\x7B-\x7F]+$)[a-z0-9A-Z\x21-\x2f\x3a-\x40\x5b-\x60\x7B-\x7F]+$/.test(
            newPassword,
          ) == false
        ) {
          createErrorModal({
            title: t('sys.api.errorTip'),
            content: '密码强度不符合要求，请重新输入。',
            getContainer: () => document.body,
          });

          return;
        }

        let params: UserModifyPasswordDto = {
          oldpwd: qcLoginPasswordEncrypt(oldPassword),
          newpwd: qcLoginPasswordEncrypt(newPassword),
          confirmpwd: qcLoginPasswordEncrypt(values.confirmpwd),
        };

        modifyPassword(params)
          .then((modifyPasswordResult) => {
            if (!modifyPasswordResult) {
              //密码修改成功后判断是否需要清除store中的提示信息
              let userLoginPrompt = userStore.getLoginPrompt;
              if (
                userLoginPrompt != undefined &&
                userLoginPrompt != null &&
                userLoginPrompt.length > 0x0
              ) {
                //如果有提示信息
                if (userLoginPrompt.match('请修改密码')) {
                  userStore.setLoginPrompt(undefined);
                }
              }
              //显示密码修改成功信息框
              notification.success({
                message: t('密码修改成功'),
                description: `密码修改成功。`,
                duration: 3,
              });

              closeModal();

              resetFields();
            } else {
              //后台接口返回提示信息
              createErrorModal({
                title: t('sys.api.errorTip'),
                content: modifyPasswordResult,
                getContainer: () => document.body,
              });

              return;
            }
          })
          .catch((ex) => {
            createErrorModal({
              title: t('sys.api.errorTip'),
              content: '修改密码异常，' + ex.msg,
              getContainer: () => document.body,
            });
          });
      }

      return {
        t,
        register,
        registerForm,
        onButtonOkClick,
      };
    },
  });
</script>
<style lang="less"></style>
